import 'package:flutter/cupertino.dart';
import 'package:flutter_base/common/sp_key.dart';
import 'package:flutter_base/common/user_helper.dart';
import 'package:flutter_base/http/api.dart';
import 'package:flutter_base/utils/sp_utils.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../bean/mine/check_app_update_entity.dart';

///
/// @DIR_PATH：lib/viewmodel/mine
/// @TIME：2024/6/13 12:29
/// @AUTHOR：starr
class MineViewModel with ChangeNotifier{

  Future exitLogin(ValueChanged<bool> callback)async{
    bool? isSuccess = await Api.instance.exitLogin();
    if(isSuccess == true){
      UserHelper.getInstance.exitLogin();
      SPUtils.removeAll();
    }
    callback.call(isSuccess ?? false);

  }

  //检查更新
  Future<String?> checkAppUpdate() async{
    var packInfo=await PackageInfo.fromPlatform();
    String versionCode = packInfo.buildNumber;
    CheckAppUpdateData data = await Api.instance.checkAppUpdate();
    String onlineAppVersionCode = data.buildBuildVersion ?? "0";
    print("lixu  ${int.tryParse(versionCode)}  ${int.tryParse(onlineAppVersionCode)}");
    try{
      if((int.tryParse(versionCode) ?? 0) < ((int.tryParse(onlineAppVersionCode) ?? 0))){
        SPUtils.save(SP_APP_VERSION, onlineAppVersionCode);
        return data.downloadURL;
      }else{
        SPUtils.save(SP_APP_VERSION, versionCode);
        return null;
      }
    }catch(e){
      SPUtils.save(SP_APP_VERSION, versionCode);
      return null;
    }
  }

  //跳转外部应用
  Future jumpToOutLink(String url)async{
    final uri = Uri.parse(url ?? "");
    if(await canLaunchUrl(uri)){
      return launchUrl(uri);
    }
    return null;
  }
}